<template>
 <div class="graphitizing">
   <div class="card-table">
      <!-- <card-uploading :show="uploading" :succeed="succeed"><span style="font-size:14px;">{{uploadText}}</span></card-uploading> -->
      <el-dialog @close="dialogClose()" title="新增装炉信息" append-to-body :modal-append-to-body="true" width="800px" :visible.sync="dialogUpload">
        <el-form class="addForm" :rules="rules1" size="small" ref="form1" :model="form" label-width="110px">
              <el-form-item label="上传Excel">
                <el-upload
                  :before-remove="()=>fileList = []"
                  class="upload-demo"
                  :file-list="fileList"
                  :before-upload="beforeUpload"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :on-change="handleChange"
                  accept="  .xlsx"
                  :limit="1"
                  :on-exceed="onExceed"
                  :auto-upload="false">
                  <el-button slot="trigger"  size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>
        </el-form>
          <span slot="footer">
            <el-button  v-loading="loading" type="primary" @click="submit">确 定</el-button>
            <el-button type="" @click="resetForm('form1')">取 消</el-button>
          </span>
      </el-dialog>
      <el-dialog class="detialDialog" top="50px"  append-to-body :modal-append-to-body="true" width="1000px" :visible.sync="dialogExcelView">
        <table class="table_Excel">
          <tr v-for="(item,index) in ExcelData" :key="index">
            <td>{{item.SMH}}</td>
            <td>{{item['石墨化装(出)炉报告单']}}</td>
            <td>{{item.__EMPTY}}</td>
            <td>{{item.__EMPTY_1}}</td>
            <td>{{item.__EMPTY_2}}</td>
            <td>{{item.__EMPTY_3}}</td>
            <td>{{item.__EMPTY_4}}</td>
            <td>{{item.__EMPTY_5}}</td>
            <td>{{item.__EMPTY_6}}</td>
            <td>{{item.__EMPTY_7}}</td>
            <td>{{item.__EMPTY_8}}</td>
            <td>{{item.__EMPTY_9}}</td>
          </tr>
        </table>
      </el-dialog>
      <!-- 第二次上传====== -->
      <el-dialog title="修改装炉Excel" custom-class="dialogStove" @close="dialogClose()" append-to-body :modal-append-to-body="true" width="800px" :visible.sync="dialogUploadThen">
        <div class="formgar">
        <el-form :rules="rules2" size="small" ref="form2" :model="form" label-width="120px">
          <div style="padding:0 24px;">
            <!-- <template v-if="!form.isTwoStove"> -->
              <el-form-item style="margin:18px 0px;margin-bottom:18px" label="上传新Excel">
                  <el-upload
                    :before-remove="()=>fileList = []"
                    class="upload-demo"
                    :file-list="fileList"
                    :before-upload="beforeUpload"
                    action="https://jsonplaceholder.typicode.com/posts/"
                    :on-change="handleChange"
                    accept="  .xlsx"
                    :limit="1"
                    :on-exceed="onExceed"
                    :auto-upload="false">
                    <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
                    <span style="margin-left:80px">当前Excel</span>
                    <el-link
                      style="padding:0;line-height:1.5;margin-left:24px;"
                      :href="form.stove.upLoadAddress"
                      type="primary">
                      {{form.stove.fileName}}
                    </el-link>
                  </el-upload>
              </el-form-item>
          </div>
        </el-form>
        </div>
        <span slot="footer">
            <el-button v-loading="loading" type="primary" @click="confirm">确 定</el-button>
            <el-button type="" @click="resetForm('form2')">取 消</el-button>
        </span>
      </el-dialog>
      <div>
      <el-button style="margin-bottom:24px;" type="primary" icon="el-icon-document-add" @click="dialogUpload = true">新 增</el-button>
      <el-button style="float:right;margin-bottom:24px;margin-right:12px;" type="primary" ><a style="color:#fff;" href="http://101.42.233.226:9000/template/石墨化装炉报告单.xlsx">模板下载</a></el-button>
      </div>
        <el-table :header-cell-style="getRowClass" :data="tableData" style="width: 100%">
          <el-table-column
            header-align="center"
            align="center"
            prop="prop"
            type="index"
            label="编号" >
          </el-table-column>
          <el-table-column prop="stove.stoveCode" label="炉号" align="center">
          </el-table-column>
          <el-table-column prop="stove.electric.totalStoveNum" sortable label="总炉数" align="center">
          </el-table-column>
          <el-table-column prop="stove.totalWeight" sortable label="总重" align="center">
          </el-table-column>
          <el-table-column prop="stove.totalNumber" sortable label="总支数" align="center">
          </el-table-column>
          <el-table-column label="送电时间" align="center" min-width="155">
            <template slot-scope="{row}">
              <span>{{row.stove.electric.startElectricTime}}</span>
            </template>
          </el-table-column>
          <el-table-column label="停电时间" align="center" min-width="155">
            <template slot-scope="{row}">
              <span>{{row.stove.electric.stopElectricTime}}</span>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" align="center" min-width="155">
            <template slot-scope="{row}">
              <span>{{row.stove.upLoadTime}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="250">
            <template slot-scope="{row}">
              <div class="tablebBtn">
                <!-- <el-button @click="showExcel(row)" size="small" type="primary" >查看</el-button> -->
                <el-button @click="showEdit(row)" size="small" type="primary" plain>编辑</el-button>
                <el-button :disabled="!row.stove.isDelete" @click="deleteOne(row._id)" size="small" type="danger">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div
          v-if="tableData.length !== 0"
          class="block"
          style="display: flex; flex-direction: row-reverse; margin-top: 10px">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :currPage-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
   </div>
 </div>
</template>

<script>
// import * as XLSX from 'xlsx/xlsx.mjs'
import { graphiteReportGet, graphiteReportDelete, graphiteReportExcelCreate, graphiteReportUpdate } from '@/api/process.js'
import { nomalPages } from '@/mixin'
// import cardUploading from '@/components/uploading.vue'

export default {
  name: '',
  components: {
    // cardUploading
  },
  mixins: [nomalPages],
  data () {
    return {
      ExcelData: null,
      dialogExcelView: false,
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      form: {
        isTwoStove: false,
        aStove: {},
        bStove: {},
        stove: {}
      },
      fileList: [],
      fileListA: [],
      fileListB: [],
      dialogUpload: false,
      dialogDetial: false,
      dialogUploadThen: false,
      uploading: false,
      succeed: false,
      uploadText: '正在上传..',
      tableData: [],
      rules1: {
        startTime: [{ required: true, message: '请输入开始送电时间', trigger: 'blur' }],
        aStoveCode: [{ required: true, message: '请输入A炉号', trigger: 'blur' }],
        bStoveCode: [{ required: true, message: '请输入B炉号', trigger: 'blur' }],
        stoveCode: [{ required: true, message: '请输入单炉炉号', trigger: 'blur' }]
      },
      rules2: {
        stopTime: [
          { required: true, message: '请输入开始送电时间', trigger: 'blur' }
        ],
        startTime: [{ required: true, message: '请输入开始送电时间', trigger: 'blur' }],
        aStoveCode: [{ required: true, message: '请输入A炉号', trigger: 'blur' }],
        bStoveCode: [{ required: true, message: '请输入B炉号', trigger: 'blur' }],
        stoveCode: [{ required: true, message: '请输入单炉炉号', trigger: 'blur' }],
        'stopElectric.aStageTime.startTime2': [{ required: true, message: '请输入开始送电时间', trigger: 'blur' }],
        'stopElectric.aStageTime.startTime1': [{ required: true, message: '请输入开始送电时间', trigger: 'blur' }],
        'stopElectric.aStageTime.stopTime1': [{ required: true, message: '请输入开始送电时间', trigger: 'blur' }],
        'stopElectric.aStageTime.stopTime2': [{ required: true, message: '请输入开始送电时间', trigger: 'blur' }],
        'stopElectric.bStageTime.startTime2': [{ required: true, message: '请输入开始送电时间', trigger: 'blur' }],
        'stopElectric.bStageTime.startTime1': [{ required: true, message: '请输入开始送电时间', trigger: 'blur' }],
        'stopElectric.bStageTime.stopTime1': [{ required: true, message: '请输入开始送电时间', trigger: 'blur' }],
        'stopElectric.bStageTime.stopTime2': [{ required: true, message: '请输入开始送电时间', trigger: 'blur' }]
      }
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    getTimeNow () {
      var dateEnd = new Date()
      this.year = dateEnd.getFullYear()
      this.month = dateEnd.getMonth() < 10 ? '0' + (dateEnd.getMonth() + 1) : dateEnd.getMonth() + 1
      this.date = dateEnd.getDate() < 10 ? '0' + dateEnd.getDate() : dateEnd.getDate()
      this.hour = dateEnd.getHours() < 10 ? '0' + dateEnd.getHours() : dateEnd.getHours()
      this.minute = dateEnd.getMinutes() < 10 ? '0' + dateEnd.getMinutes() : dateEnd.getMinutes()
      this.second = dateEnd.getSeconds() < 10 ? '0' + dateEnd.getSeconds() : dateEnd.getSeconds()
      var currentTime = this.year + '-' + this.month + '-' + this.date + ' ' + this.hour + ':' + this.minute + ':' + this.second
      return currentTime
    },
    // showExcel (row) {
    //   const _this = this
    //   _this.$http({
    //     method: 'get',
    //     url: row.stove.upLoadAddress,
    //     responseType: 'arraybuffer'
    //   }).then(res => {
    //     const data = new Uint8Array(res.data)
    //     const workbook = XLSX.read(data, { type: 'array' })
    //     console.log(workbook)
    //     // const sheetNames = workbook.SheetNames // 工作表名称集合
    //     // _this.workbook = workbook
    //     const worksheet = workbook.Sheets['石墨化装出炉报告单']
    //     _this.ExcelData = XLSX.utils.sheet_to_json(worksheet)
    //     this.dialogExcelView = true
    //     // dataNow 现在就是json格式的数组，里面的表头可以作为表格的表头，vue 直接使用v-for去做就好了，
    //   })
    // },
    showEdit (row) {
      this.dialogUploadThen = true
      this.form = JSON.parse(JSON.stringify(row))
    },
    showDetial (row) {
      this.dialogDetial = true
      this.form = JSON.parse(JSON.stringify(row))
    },
    getAllData () {
      const params = {
        pageSize: this.pageSize,
        currPage: this.currentPage
      }
      graphiteReportGet(params).then(res => {
        console.log(res)
        if (res.data.code === 200) {
          this.tableData = res.data.data.pageData
          this.total = res.data.data.total
        }
      })
    },
    beforeFileListChange (file, fileList, fileName) {
      console.log(file)
      const fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
      const fileSize = Number(file.size / 1024 / 1024)
      console.log('上传文件大小为 ', fileSize + ' MB')
      console.log('上传文件类型为 ', fileType)
      if (fileSize > 2) {
        this[fileName] = fileList.slice(0, 0)
        this.$message('上传文件不能超过2MB')
      } else {
        if (fileType === 'xlsx') {
          this[fileName] = fileList.slice(-1)
        } else {
          this.$message.warning('请上传正确Excel文件')
          this[fileName] = fileList.slice(0, 0)
        }
      }
    },
    beforeUpload () {
      // console.log('beforefile', file)
    },
    handleChange (file, fileList) {
      this.beforeFileListChange(file, fileList, 'fileList')
    },
    handleChangeA (file, fileList) {
      // console.log(file, fileList)
      this.beforeFileListChange(file, fileList, 'fileListA')
    },
    handleChangeB (file, fileList) {
      // console.log(file, fileList)
      this.beforeFileListChange(file, fileList, 'fileListB')
    },
    deleteOne (_id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        graphiteReportDelete(_id).then(res => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getAllData()
          } else {
            this.$message({
              type: 'warging',
              message: res.data.message
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    onExceed () {
      this.$message({
        message: '已选择文件，不可上传多个文件'
      })
    },
    submit () {
      this.$refs.form1.validate((valid) => {
        if (valid) {
          var formdata = new FormData()
          const file = this.fileList[0]
          const fileA = this.fileListA[0]
          const fileB = this.fileListB[0]
          if (this.form.isTwoStove) {
            if (fileA && fileB) {
              formdata.append('file', this.fileListA[0].raw)
              formdata.append('file', this.fileListB[0].raw)
            } else {
              this.$message.warning('请先上传两炉Excel文件再提交')
              return
            }
          } else {
            if (file) {
              formdata.append('file', this.fileList[0].raw)
            } else {
              this.$message.warning('请先上传Excel文件再提交')
              return
            }
          }
          this.loading = true
          formdata.append('form', JSON.stringify(this.form))
          graphiteReportExcelCreate(formdata).then(res => {
            if (res.data.code === 200) {
              this.$message.success('上传成功')
              this.getAllData()
              this.dialogUpload = false
            } else {
              this.$message.warning(res.data.message)
            }
            this.loading = false
            this.dialogUpload = false
          }).catch(error => {
            this.loading = false
            console.log(error)
            this.dialogUpload = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    upload () {
      var formdata = new FormData()
      const fileA = this.fileListA[0]
      const fileB = this.fileListB[0]
      if (this.form.isTwoStove) {
        const a = fileA && fileB
        const b = !fileA && !fileB
        if (a) {
          formdata.append('file', this.fileListB[0].raw)
          formdata.append('file', this.fileListA[0].raw)
        } else if (b) {
        } else {
          const text = '请上传' + (fileA ? 'B' : 'A') + '炉Excel'
          this.$message.warning(text)
          return
        }
      } else {
        if (this.fileList[0]) {
          formdata.append('file', this.fileList[0].raw)
        }
      }
      console.log(formdata.getAll('file'))
      this.loading = true
      // this.form.stove.upLoadTime = this.getTimeNow()
      formdata.append('form', JSON.stringify(this.form))
      graphiteReportUpdate(formdata).then(res => {
        if (res.data.code === 200) {
          this.$message.success('修改成功')
          this.fileList = []
          this.dialogUploadThen = false
          this.getAllData()
        } else {
          this.$message.warning(res.data.message)
        }
        this.loading = false
        this.dialogUploadThen = false
      }).catch(error => {
        this.loading = false
        console.log(error)
        this.dialogUploadThen = false
      })
    },
    confirm () {
      this.$refs.form2.validate((valid) => {
        if (valid) {
          if (this.form.isOk) {
            this.$confirm('提交完成后,将汇总数据,不再支持更改, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.upload()
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消更改'
              })
            })
          } else {
            this.upload()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    dialogClose () {
      this.form = this.$options.data().form
      this.fileList = []
      this.fileListA = []
      this.fileListB = []
      if (this.$refs.form1) {
        this.$refs.form1.resetFields()
      }
      if (this.$refs.form2) {
        this.$refs.form2.resetFields()
      }
    },
    resetForm (formName) {
      this.dialogUpload = false
      this.dialogUploadThen = false
      this.form = this.$options.data().form
      this.fileList = []
      this.fileListA = []
      this.fileListB = []
      this.$refs[formName].resetFields()
    }

  }
}
</script>

<style  scoped>
.card-search{
  padding-bottom: 10px;
}
.tablebBtn .el-button{
  padding: 8px 14px;
}
.el-divider {
  margin: 30px 0;
}
.el-link{
  line-height: 1;
  padding-bottom: 12px;
}
.dialogTitle{
  padding: 18px;
  font-size: 18px;
}
.isTow{
    .el-radio-button:first-child .el-radio-button__inner{
    border-radius:2px 0 0 2px;
  }
    .el-radio-button:last-child .el-radio-button__inner{
    border-radius:0 2px 2px 0;
  }
   .is-active .el-radio-button__inner{
    background-color: $primary;
    border-color: $primary;
  }
}
.table_Excel {
  width: 100%;
  border-collapse: collapse;
  th,td{
    border: 1px solid #999;
    text-align: center;
    padding: 10px 0;
    width: 120px;
  }
  tr:hover{
    background-color: #ccc;
  }
}

</style>
<style >
.detialDialog .el-dialog__header{
  padding: 0;
}
.detialDialog {
  padding: 12px;
}
</style>
